
/**
 * 媒体处理工具
 */

// 处理媒体上传
function processMediaUpload(options) {
  const { mediaType, tempFiles, tempVideo, currentDesc, userInfo, context } = options;
  
  return new Promise((resolve, reject) => {
    // 上传媒体文件到云存储
    const uploadTasks = [];
    const fileIDs = [];
    const fileURLs = [];
    
    if (mediaType === 'image' && tempFiles.length > 0) {
      // 上传多张图片
      tempFiles.forEach((filePath, index) => {
        const cloudPath = `art/images/${Date.now()}-${index}${filePath.match(/\.[^.]+?$/)[0] || '.png'}`;
        uploadTasks.push(
          wx.cloud.uploadFile({
            cloudPath: cloudPath,
            filePath: filePath
          }).then(res => {
            fileIDs.push(res.fileID);
            return wx.cloud.getTempFileURL({
              fileList: [res.fileID]
            });
          }).then(urlRes => {
            fileURLs.push(urlRes.fileList[0].tempFileURL);
          })
        );
      });
    } else if (mediaType === 'video' && tempVideo) {
      // 上传视频
      const cloudPath = `art/videos/${Date.now()}${tempVideo.match(/\.[^.]+?$/)[0] || '.mp4'}`;
      uploadTasks.push(
        wx.cloud.uploadFile({
          cloudPath: cloudPath,
          filePath: tempVideo
        }).then(res => {
          fileIDs.push(res.fileID);
          return wx.cloud.getTempFileURL({
            fileList: [res.fileID]
          });
        }).then(urlRes => {
          fileURLs.push(urlRes.fileList[0].tempFileURL);
        })
      );
    }
    
    // 执行所有上传任务
    Promise.all(uploadTasks).then(() => {
      // 将内容信息保存到云数据库
      return wx.cloud.callFunction({
        name: 'contentManager',
        data: {
          action: 'addContent',
          content: currentDesc.trim(),
          mediaType: mediaType,
          fileIDs: fileIDs,
          fileURLs: fileURLs,
          userInfo: userInfo || {}
        }
      });
    }).then(res => {
      console.log('保存内容结果:', res);
      if (res.result && res.result.success) {
        // 创建新项目
        const newItem = {
          id: res.result.contentID || ('new-' + Date.now()),
          userAvatar: userInfo && userInfo.avatarUrl ? userInfo.avatarUrl : '/images/default_avatar.png',
          userName: userInfo && userInfo.nickName ? userInfo.nickName : '匿名用户',
          fileURLs: mediaType === 'image' ? tempFiles : (tempVideo ? [tempVideo] : []),
          fileIDs: fileIDs,
          mediaType: mediaType,
          description: currentDesc.trim(),
          createTime: new Date().toLocaleString(),
          isLiked: false,
          likeCount: 0,
          comments: []
        };
        
        // 延迟更新图片URL
        setTimeout(() => {
          if (fileIDs.length > 0) {
            wx.cloud.getTempFileURL({
              fileList: fileIDs,
              success: urlRes => {
                if (urlRes.fileList && urlRes.fileList.length > 0) {
                  const tempURLs = urlRes.fileList.map(file => file.tempFileURL);
                  console.log('延迟获取临时URL成功:', tempURLs);
                  
                  // 更新列表中的图片URL
                  const index = context.data.artList.findIndex(item => item.id === newItem.id);
                  if (index !== -1) {
                    context.setData({
                      [`artList[${index}].fileURLs`]: tempURLs
                    });
                  }
                }
              }
            });
          }
        }, 1000);
        
        resolve(newItem);
      } else {
        reject(new Error('保存内容失败'));
      }
    }).catch(err => {
      console.error('上传失败:', err);
      reject(err);
    });
  });
}

module.exports = {
  processMediaUpload
};